package cn.sfrog.project.biz.admin.task;

import cn.sfrog.project.biz.admin.pay.PayFactory;
import lombok.SneakyThrows;

import java.util.concurrent.TimeUnit;

/**
 * 订单轮询任务
 */
public class OrderStatusQueryTask implements Runnable{
    private final Integer minutes;
    private final String sn;
    private final PayFactory payFactory;
    public OrderStatusQueryTask(Integer minutes, String sn, PayFactory payFactory){
        this.minutes = minutes < 1 ? 1:minutes;
        this.sn = sn;
        this.payFactory = payFactory;
    }

    @SneakyThrows
    @Override
    public void run() {
        int step = 1;
        int total = minutes;

        boolean isPay = false;
        while (total > 0){
            try{
                isPay = payFactory.queryPayStatus(sn);
                if(isPay){
                    break;
                }
                TimeUnit.MINUTES.sleep(step);
                total -= step;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        if(!isPay){
            payFactory.closeOrder(sn);
        }

    }
}
